package org.jeecg.modules.demo.projectroom.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.demo.applyinfo.entity.ZnzfApply;
import org.jeecg.modules.demo.applyinfo.service.IZnzfApplyService;
import org.jeecg.modules.demo.projectroom.entity.*;
import org.jeecg.modules.demo.projectroom.service.IZnzfProjectProvinceService;
import org.jeecg.modules.demo.projectroom.service.IZnzfProjectTypeService;
import org.jeecg.modules.demo.roomapartdistribute.entity.ZnzfRoomApartDistribute;
import org.jeecg.modules.demo.roomapartdistribute.service.IZnzfRoomApartDistributeService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.projectroom.service.IZnzfProjectService;
import org.jeecg.modules.demo.projectroom.service.IZnzfRoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 项目表
 * @Author: jeecg-boot
 * @Date:   2022-04-09
 * @Version: V1.0
 */
@Api(tags="项目表")
@RestController
@RequestMapping("/projectroom/znzfProject")
@Slf4j
public class ZnzfProjectController extends JeecgController<ZnzfProject, IZnzfProjectService> {

	@Autowired
	private IZnzfProjectService znzfProjectService;

	@Autowired
	private IZnzfRoomService znzfRoomService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private IZnzfProjectTypeService znzfProjectTypeService;
    @Autowired
    private IZnzfRoomApartDistributeService znzfRoomApartDistributeService;
    @Autowired
    private IZnzfApplyService znzfApplyService;
	 @Autowired
	 private IZnzfProjectProvinceService znzfProjectProvinceService;

	/**
	 * 分页列表查询
	 * @param znzfProject
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "项目表-分页列表查询")
	@ApiOperation(value="项目表-分页列表查询", notes="项目表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ZnzfProject znzfProject,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ZnzfProject> queryWrapper = QueryGenerator.initQueryWrapper(znzfProject, req.getParameterMap());
		Page<ZnzfProject> page = new Page<ZnzfProject>(pageNo, pageSize);
		IPage<ZnzfProject> pageList = znzfProjectService.page(page, queryWrapper);
		return Result.OK(pageList);

    }

     @AutoLog(value = "项目表-通过类型分页查询")
     @ApiOperation(value="项目表-通过类型分页查询", notes="项目表-通过类型分页查询")
     @GetMapping(value = "/listByTypes")
     public Result<?> listByTypes(ZnzfProject znzfProject,@RequestParam(name="filterType", required = false) String filterType,
                                    @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                    @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                    HttpServletRequest req) {
         QueryWrapper<ZnzfProject> queryWrapper = QueryGenerator.initQueryWrapper(znzfProject, req.getParameterMap());
         if(oConvertUtils.isNotEmpty(filterType)){
         	 String[] types = filterType.split(",");
             queryWrapper.eq("type",Integer.parseInt(types[0]));
			 if(types.length > 1){
                 for(int i = 1; i < types.length; i++){
                     queryWrapper.or().eq("type", Integer.parseInt(types[i]));
                 }
             }
         }
         Page<ZnzfProject> page = new Page<ZnzfProject>(pageNo, pageSize);
         IPage<ZnzfProject> pageList = znzfProjectService.page(page, queryWrapper);
         return Result.OK(pageList);
     }

	@AutoLog(value = "项目表-通过项目id查询项目")
	@ApiOperation(value="项目表-通过项目id查询项目", notes="项目表-通过项目id查询项目")
	@GetMapping(value = "/searchById")
	public Result<ZnzfProject> searchById(@RequestParam(name="projectId") String projectId, HttpServletRequest request) {
		String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		String tmp = JwtUtil.getUsername(token);
		SysUser sysUser = sysUserService.getUserByName(tmp);
		if(oConvertUtils.isEmpty(sysUser))
			return Result.error("账号异常");
		ZnzfProject znzfProject = znzfProjectService.getById(projectId);
		ZnzfProjectType znzfProjectType = znzfProjectTypeService.searchByValue(znzfProject.getType() + "");
		znzfProject.setType_direct(znzfProjectType.getName());
		return Result.OK(znzfProject);
	}

    @AutoLog(value = "项目表-通过房源单位分配id查询项目")
    @ApiOperation(value="项目表-通过房源单位分配id查询项目", notes="项目表-通过房源单位分配id查询项目")
    @GetMapping(value = "/searchByRadId")
    public Result<ZnzfProject> searchByRadId(@RequestParam(name="radId") String radId, HttpServletRequest request) {
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String tmp = JwtUtil.getUsername(token);
        SysUser sysUser = sysUserService.getUserByName(tmp);
        if(oConvertUtils.isEmpty(sysUser))
            return Result.error("账号异常");
        ZnzfRoomApartDistribute znzfRoomApartDistribute = znzfRoomApartDistributeService.getById(radId);
        ZnzfApply znzfApply = znzfApplyService.getById(znzfRoomApartDistribute.getApplyInfo());
        ZnzfProject znzfProject = znzfProjectService.getById(znzfApply.getProject());
        ZnzfProjectType znzfProjectType = znzfProjectTypeService.searchByValue(znzfProject.getType() + "");
        znzfProject.setType_direct(znzfProjectType.getName());
        return Result.OK(znzfProject);
    }

	/**
     *   添加
     * @param znzfProject
     * @return
     */
    @AutoLog(value = "项目表-添加")
    @ApiOperation(value="项目表-添加", notes="项目表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ZnzfProject znzfProject) {
        znzfProjectService.save(znzfProject);
        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     * @param znzfProject
     * @return
     */
    @AutoLog(value = "项目表-编辑")
    @ApiOperation(value="项目表-编辑", notes="项目表-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<?> edit(@RequestBody ZnzfProject znzfProject) {
        znzfProjectService.updateById(znzfProject);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "项目表-通过id删除")
    @ApiOperation(value="项目表-通过id删除", notes="项目表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        znzfProjectService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "项目表-批量删除")
    @ApiOperation(value="项目表-批量删除", notes="项目表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.znzfProjectService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZnzfProject znzfProject) {
        return super.exportXls(request, znzfProject, ZnzfProject.class, "项目表");
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ZnzfProject.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/
	

    /*--------------------------------子表处理-房源表-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "房源表-通过主表ID查询")
	@ApiOperation(value="房源表-通过主表ID查询", notes="房源表-通过主表ID查询")
	@GetMapping(value = "/listZnzfRoomByMainId")
    public Result<?> listZnzfRoomByMainId(ZnzfRoom znzfRoom,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<ZnzfRoom> queryWrapper = QueryGenerator.initQueryWrapper(znzfRoom, req.getParameterMap());
        Page<ZnzfRoom> page = new Page<ZnzfRoom>(pageNo, pageSize);
        IPage<ZnzfRoom> pageList = znzfRoomService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param znzfRoom
	 * @return
	 */
	@AutoLog(value = "房源表-添加")
	@ApiOperation(value="房源表-添加", notes="房源表-添加")
	@PostMapping(value = "/addZnzfRoom")
	public Result<?> addZnzfRoom(@RequestBody ZnzfRoom znzfRoom) {
		znzfRoomService.save(znzfRoom);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param znzfRoom
	 * @return
	 */
	@AutoLog(value = "房源表-编辑")
	@ApiOperation(value="房源表-编辑", notes="房源表-编辑")
	@RequestMapping(value = "/editZnzfRoom", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<?> editZnzfRoom(@RequestBody ZnzfRoom znzfRoom) {
		znzfRoomService.updateById(znzfRoom);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "房源表-通过id删除")
	@ApiOperation(value="房源表-通过id删除", notes="房源表-通过id删除")
	@DeleteMapping(value = "/deleteZnzfRoom")
	public Result<?> deleteZnzfRoom(@RequestParam(name="id",required=true) String id) {
		znzfRoomService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "房源表-批量删除")
	@ApiOperation(value="房源表-批量删除", notes="房源表-批量删除")
	@DeleteMapping(value = "/deleteBatchZnzfRoom")
	public Result<?> deleteBatchZnzfRoom(@RequestParam(name="ids",required=true) String ids) {
	    this.znzfRoomService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportZnzfRoom")
    public ModelAndView exportZnzfRoom(HttpServletRequest request, ZnzfRoom znzfRoom) {
		 // Step.1 组装查询条件
		 QueryWrapper<ZnzfRoom> queryWrapper = QueryGenerator.initQueryWrapper(znzfRoom, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<ZnzfRoom> pageList = znzfRoomService.list(queryWrapper);
		 List<ZnzfRoom> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "房源表"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, ZnzfRoom.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("房源表报表", "导出人:" + sysUser.getRealname(), "房源表"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importZnzfRoom/{mainId}")
    public Result<?> importZnzfRoom(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<ZnzfRoom> list = ExcelImportUtil.importExcel(file.getInputStream(), ZnzfRoom.class, params);
				 for (ZnzfRoom temp : list) {
                    temp.setProjectId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 znzfRoomService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-房源表-end----------------------------------------------*/

	/**
	 * 统计各站段房源情况
	 *
	 * @return
	 */
	@AutoLog(value = "房源表-统计各站段房源情况")
	@ApiOperation(value="房源表-统计各站段房源情况", notes="房源表-统计各站段房源情况")
	@GetMapping(value = "/countRoomCntByStation")
	public Result<Map<String, Integer>> countRoomCntByStation() {
        Map<String, Integer> resList = znzfProjectService.countRoomCntByStation();
		return Result.OK(resList);
	}


     /**
      * 查询某个站段的房源具体情况（返回房间类型，状态，数量）(station为null则统计所有站段房源情况，否则统计指定station房源情况)
      *
      * @param station 站段名称
      * @return
      */
     @AutoLog(value = "房源表-查询某个站段的房源具体情况")
     @ApiOperation(value="房源表-查询某个站段的房源具体情况", notes="房源表-查询某个站段的房源具体情况")
     @GetMapping(value = "/countRoomTypeCntByStation")
     public Result<List<ZnzfStationParam>> countRoomTypeCntByStation(@RequestParam(name="station",required=false) String station) {
         List<ZnzfStationParam> resList = znzfProjectService.countRoomTypeCntByStation(station);
		 if (resList.size() == 1 && resList.get(0).getRoomStateParamList().size()==0) {
			 return Result.error("未查到相应数据",null);
		 }
         return Result.OK(resList);
     }

	 /**
	  * 查询项目树状结构
	  * @param request
	  * @return
	  */
	 @AutoLog(value = "房源表-查询项目树状结构")
	 @ApiOperation(value="房源表-查询项目树状结构", notes="房源表-查询项目树状结构")
	 @GetMapping(value = "/projectTree")
	 public Result<List<ZnzfProjectTree>> projectTree(HttpServletRequest request) {
		 String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		 String tmp = JwtUtil.getUsername(token);
		 SysUser sysUser = sysUserService.getUserByName(tmp);
		 if(oConvertUtils.isEmpty(sysUser))
			 return Result.error("账号异常");
		 List<ZnzfProjectTree> znzfProjectTreeList = new ArrayList<>();
		 //省
		 List<ZnzfProjectProvince> province1 = znzfProjectProvinceService.getChildrenByPid("1");
		 if(oConvertUtils.isNotEmpty(province1)){
		 	for(ZnzfProjectProvince znzfProjectProvince1 : province1){
		 		List<ZnzfProjectTree> znzfProjectTreeList1 = new ArrayList<>();
		 		//公寓段
				List<ZnzfProjectProvince> province2 = znzfProjectProvinceService.getChildrenByPid(znzfProjectProvince1.getTureid());
				if(oConvertUtils.isNotEmpty(province2)) {
					for (ZnzfProjectProvince znzfProjectProvince2 : province2) {
						List<ZnzfProjectTree> znzfProjectTreeList2 = new ArrayList<>();
						//城市
						List<ZnzfProjectProvince> province3 = znzfProjectProvinceService.getChildrenByPid(znzfProjectProvince2.getTureid());
						if(oConvertUtils.isNotEmpty(province3)) {
							for (ZnzfProjectProvince znzfProjectProvince3 : province3) {
								List<ZnzfProjectTree> znzfProjectTreeList3 = new ArrayList<>();
								//项目
								List<ZnzfProject> znzfProjectList = znzfProjectService.searchsByCity(znzfProjectProvince3.getName());
								if(oConvertUtils.isNotEmpty(znzfProjectList)){
									for(ZnzfProject znzfProject : znzfProjectList){
										ZnzfProjectTree znzfProjectTree4 = new ZnzfProjectTree();
										znzfProjectTree4.setId(znzfProject.getId());
										znzfProjectTree4.setChildren(null);
										znzfProjectTree4.setKey(znzfProject.getNo());
										znzfProjectTree4.setTitle(znzfProject.getName());
										znzfProjectTree4.setDisabled(true);
										znzfProjectTreeList3.add(znzfProjectTree4);
									}
								}
								ZnzfProjectTree znzfProjectTree3 = new ZnzfProjectTree();
								znzfProjectTree3.setId(znzfProjectProvince2.getId());
								if(oConvertUtils.isNotEmpty(znzfProjectTreeList3))
									znzfProjectTree3.setChildren(znzfProjectTreeList3);
								znzfProjectTree3.setKey(znzfProjectProvince2.getTureid());
								znzfProjectTree3.setTitle(znzfProjectProvince2.getName());
								znzfProjectTreeList2.add(znzfProjectTree3);
							}
						}
						ZnzfProjectTree znzfProjectTree2 = new ZnzfProjectTree();
						znzfProjectTree2.setId(znzfProjectProvince1.getId());
						if(oConvertUtils.isNotEmpty(znzfProjectTreeList2))
							znzfProjectTree2.setChildren(znzfProjectTreeList2);
						znzfProjectTree2.setKey(znzfProjectProvince1.getTureid());
						znzfProjectTree2.setTitle(znzfProjectProvince1.getName());
						znzfProjectTreeList1.add(znzfProjectTree2);
					}
				}
				ZnzfProjectTree znzfProjectTree1 = new ZnzfProjectTree();
				znzfProjectTree1.setId(znzfProjectProvince1.getId());
				if(oConvertUtils.isNotEmpty(znzfProjectTreeList1))
					znzfProjectTree1.setChildren(znzfProjectTreeList1);
				znzfProjectTree1.setKey(znzfProjectProvince1.getTureid());
				znzfProjectTree1.setTitle(znzfProjectProvince1.getName());
				znzfProjectTreeList.add(znzfProjectTree1);
			}
		 }
		 return Result.OK(znzfProjectTreeList);
	 }
}
